package com.jjty.dataGenerator.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jjty.dataGenerator.common.RedisKey;
import com.jjty.dataGenerator.utils.JWTUtils;
import com.jjty.dataGenerator.utils.RedisUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: huangyulong
 * @createTime: 2023-04-04- 15:26
 * @Description: 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 访问控制器方法前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //处理CORS之前的请求跨域拦截
        if ("OPTIONS".equals(request.getMethod().toUpperCase())) {
            return true;
        }

        String token = request.getHeader("token");
        Map<String,Object> map = new HashMap<>();
        map.put("code",-1);
        try{
            JWTUtils.verify(token);
            Map<String, String> claims = JWTUtils.getTokenInfo(token);
            if(RedisUtils.stringRedis.hasKey(RedisKey.LOGIN+claims.get("id"))){
                //如果key还未过期,延长key的时间
                RedisUtils.stringRedis.expire(RedisKey.LOGIN+claims.get("id"), 12, TimeUnit.HOURS);
            }else{
                throw new TokenExpiredException("token已过期");
            }
            return true;
        }catch (SignatureVerificationException e){
            map.put("msg", "无效签名");
        } catch (TokenExpiredException e){
            map.put("msg", "token已过期");
        } catch (AlgorithmMismatchException e) {
            map.put("msg", "token算法不一致");
        } catch (NullPointerException e){
            map.put("msg", "请先登录");
        }catch (Exception e){
            map.put("code",500);
            map.put("msg", e.getMessage());
        }

        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(json);
        return false;
    }

    /**
     * 访问控制器方法后执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * postHandle方法执行完成后执行，一般用于释放资源
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
